#!/usr/bin/env python
# -*- coding: UTF-8 -*-
"""
# File          ：sub_process_view.py
# Time          ：2024/8/18 14:25 
# Author        ：Y-aong
# version       ：python 3.10
# Description   : 子流程参数
"""
from flask_restx import fields

from apis.flow import flow_ns
from apis.flow.schema.task_node_schema import SubProcessParamsSchema
from apis.orderlines.models import Variable
from public.api_utils.api_decorator import handle_api_error
from public.base_model import db
from public.base_response import generate_response, MarshalModel
from public.base_view import AbstractView

sub_process_get = {
    'process_id': fields.String(description='流程ID'),
}
sub_process_item = {
    'process_id': fields.String(description='流程ID'),
    'variable_key': fields.String(description='变量名称'),
    'variable_value': fields.String(description='变量值'),
    'variable_type': fields.String(description='变量类型'),
    'variable_desc': fields.String(description='变量描述'),
}

sub_process_get_marshal = MarshalModel('sub_process_get', flow_ns)
sub_process_marshal = MarshalModel('sub_process', flow_ns)


class SubProcessView(AbstractView):
    url = '/sub_process/param'

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.process_id = self.form_data.get('process_id')

    @handle_api_error()
    @flow_ns.doc(description='获取子流程参数')
    @flow_ns.expect(sub_process_get_marshal.detail_request(sub_process_get))
    @flow_ns.marshal_with(sub_process_get_marshal.list_response(sub_process_item, True, False))
    def get(self):
        """获取子流程参数"""
        with db.auto_commit():
            objs = db.session.query(Variable).filter(
                Variable.process_id == self.process_id,
                Variable.active == 1
            ).all()
            sub_subprocess = SubProcessParamsSchema().dump(objs, many=True)
        return generate_response(data=sub_subprocess, message='获取子流程参数成功')

    @handle_api_error()
    @flow_ns.doc(description='修改子流程参数')
    @flow_ns.expect(sub_process_marshal.detail_request(sub_process_item))
    @flow_ns.marshal_with(sub_process_marshal.message_response())
    def post(self):
        """修改子流程参数"""
        with db.auto_commit():
            db.session.query(Variable).filter(
                Variable.process_id == self.process_id,
                Variable.variable_key == self.form_data.get('variable_key')
            ).update(self.form_data)
        return generate_response(message='子流程参数修改成功！')
